package helpers

import (
  "os"

  "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type Oss struct {
}

func NewOss() *Oss {
  return &Oss{}
}

func (o *Oss) Transmit(bucketName, remoteDir, localFile string, contentType string) (string, error) {
  endpoint, _ := os.LookupEnv("oss_endpoint")
  accessKeyID, _ := os.LookupEnv("oss_access_key_id")
  accessKeySecret, _ := os.LookupEnv("oss_access_key_secret")

  defer os.Remove(localFile)

  client, err := oss.New(endpoint, accessKeyID, accessKeySecret)
  if err != nil {
    return "", err
  }

  bucket, err := client.Bucket(bucketName)
  if err != nil {
    return "", err
  }

  objectKey := remoteDir + "/" + NewHash().CreateFileName(localFile)
  err = bucket.PutObjectFromFile(objectKey, localFile, oss.ContentType(contentType))
  if err != nil {
    return "", err
  }

  return objectKey, nil
}
